<template>
  <div class="cc-form">
    <div class="header">
      <slot name="header"></slot>
    </div>
    <el-form :label-width="labelWidth">
      <el-row>
        <template v-for="item in formItems" :key="item.label">
          <el-col v-bind="colLayout">
            <el-form-item
              :label="item.label"
              :rules="item.rules"
              :style="itemStyle"
            >
              <template
                v-if="item.type === 'input' || item.type === 'password'"
              >
                <el-input
                  :placeholder="item.placeholder"
                  :show-password="item.type === 'password'"
                  :model-value="modelValue[`${item.field}`]"
                  @update:modelValue="handleValueChange($event, item.field)"
                ></el-input>
              </template>

              <template v-if="item.type === 'select'">
                <el-select
                  :placeholder="item.placeholder"
                  style="width: 100%"
                  :model-value="modelValue[`${item.field}`]"
                  @update:modelValue="handleValueChange($event, item.field)"
                >
                  <el-option
                    v-for="opt in item.options"
                    :value="opt.value"
                    :key="opt.value"
                  >
                    {{ opt.label }}
                  </el-option>
                </el-select>
              </template>

              <template v-if="item.type === 'datepicker'">
                <el-date-picker
                  v-bind="item.otherOptions"
                  style="width: 100%"
                  :model-value="modelValue[`${item.field}`]"
                  @update:modelValue="handleValueChange($event, item.field)"
                ></el-date-picker>
              </template>
            </el-form-item>
          </el-col>
        </template>
      </el-row>

      <div class="footer">
        <slot name="footer"></slot>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType, computed, ref, watch } from "vue";
import { IFormItem } from "../types";
import {
  ElForm,
  ElRow,
  ElCol,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElOptionGroup,
  ElDatePicker,
} from "element-plus";

export default defineComponent({
  components: {
    ElForm,
    ElRow,
    ElCol,
    ElFormItem,
    ElInput,
    ElSelect,
    ElOption,
    ElOptionGroup,
    ElDatePicker,
  },
  props: {
    modelValue: {
      type: Object,
      required: true,
    },
    formItems: {
      type: Array as PropType<IFormItem[]>,
      default: () => [], // vue3 设定默认值时如果默认值是数组或者对象必须使用箭头函数，如果是基本类型可以直接赋值
    },
    labelWidth: {
      type: String,
      default: "100px",
    },
    itemStyle: {
      type: Object,
      default: () => ({ padding: "10px 40px" }),
    },
    colLayout: {
      type: Object,
      default: () => ({
        xl: 6, // 栅格布局中占据4个空间（横向总共24个），即一行布局4个 item
        lg: 8,
        md: 12,
        sm: 24,
        xs: 24,
      }),
    },
  },
  emits: ["update:modelValue"],
  setup(props, { emit }) {
    const handleValueChange = (value: any, field: string) => {
      emit("update:modelValue", { ...props.modelValue, [field]: value });
    };

    // 弃用二：coderwhy 的方法，在后台实现了双向绑定，但是UI上没有即使刷新显示
    // const formData = ref({ ...props.modelValue })
    // watch(formData, (newValue) => emit('update:modelValue', newValue), { deep: true })

    // 弃用一：封装实现双向绑定时弃用下面的方法 coderwhy 不建议使用该方法
    // const formData = computed({
    //   get: () => props.modelValue,
    //   set: (newVal) => {
    //     emit('update:modelValue', newVal)
    //   }
    // })
    return { handleValueChange };
  },
});
</script>
<style scoped>
/* el-form 的 form-item 有默认的下方的 margin = 22px，这里设置上面也是22px ，看上去更协调 */
.cc-form {
  padding-top: 22px;
}

.form-item {
  padding: 5px 30px;
}
</style>
